// pages/cart/cart.js
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    total: 0,
    list: [],
    time: 3,
    timeId: null,
    isLogin: false,
    //默认不显示底部提交栏
    notShowBar: true,
    productDetails: [],
    lastNum: 0
  },
  isLogin() {
    let res = wx.getStorageSync('userInfo')
    if (!res) {
      this.setData({
        isLogin: false
      })
      // 每次点击结算,都需要将倒计时秒数还原
      this.data.time = 3
      // 展示倒计时弹框
      wx.showToast({
        title: '请先登录，' + this.data.time + '秒后跳转',
        icon: "none",
        duration: 1000,
      })
      // 使用setInterval 实现倒计时
      this.data.timeId = setInterval(() => {
        // 秒数每次减1
        this.data.time -= 1
        // 做一个判断,如果秒数为0的话清除定时器
        if (this.data.time <= 0) {
          clearInterval(this.data.timeId)
          // 进行页面跳转
          wx.switchTab({
            url: '/pages/my/my'
          })
        }
        //定时器每循环一次调一次弹窗
        if (this.data.time > 0) {
          wx.showToast({
            title: '请先登录，' + this.data.time + '秒后跳转',
            icon: "none",
            duration: 1000
          })
        }
        return
      }, 1000)
    } else {
      this.setData({
        isLogin: true
      })
    }
  },
  // 计算合计
  onTotal() {
    let res = this.data.list.filter(item => item.state !== false).reduce((total, item) => {
      return total += item.price * item.count
    }, 0)
    this.setData({
      total: res
    })
  },
  // count改变事件
  onCountChange(e) {
    let newList = []
    let that = this
    newList = this.data.list
    wx.cloud.database().collection('cart').doc(e.currentTarget.dataset.id).update({
      data: {
        count: e.detail
      },
      success: function (res) {
        console.log("更改" + e.currentTarget.dataset.id + "商品的购物车数量为" + e.detail)
        newList[e.currentTarget.dataset.index].count = e.detail;
        that.setData({
          list: newList
        })
        that.onTotal()
      }
    })
  },
  onCheck(id, p_id, index, num) {
    let newList = []
    newList = this.data.list
    app.getOne("product_details", p_id)
      .then(res => {
        this.setData({
          lastNum: res.data.gross - res.data.sale
        })
        if (!newList[index].state && this.data.lastNum < num && this.data.lastNum != 0) {
          wx.showToast({
            title: '抱歉,' + newList[index].name + '还剩' + this.data.lastNum + '件',
            icon: 'none'
          })
        } else if (!newList[index].state && this.data.lastNum == 0) {
          wx.showToast({
            title: '抱歉，' + newList[index].name + '售空了',
            icon: 'none'
          })
        } else {
          app.db("cart").doc(id)
            .update({
              data: {
                state: !newList[index].state
              }
            })
            .then(res => {
              newList[index].state = !this.data.list[index].state
              this.setData({
                list: newList,
              });
              // 全选判断
              let er = newList.some(item => {
                return item.state === false
              })
              this.setData({
                checked: !er
              })
              // 复选框改变，计算总价
              this.onTotal()
            })
        }
      })
  },
  // 复选框事件
  onCheckedChange(e) {
    this.onCheck(e.currentTarget.dataset.id, e.currentTarget.dataset.p_id, e.currentTarget.dataset.index, e.currentTarget.dataset.num)
  },
  // 全选按钮改变事件
  submitOnChange(event) {
    // 全选对应商品全选
    console.log(event.detail)
    for (let i = 0; i < this.data.list.length; i++) {
      if (event.detail && !this.data.list[i].state) {
        this.onCheck(this.data.list[i]._id, this.data.list[i].id, i, this.data.list[i].count)
      } else if (!event.detail && this.data.list[i].state) {
        this.onCheck(this.data.list[i]._id, this.data.list[i].id, i, this.data.list[i].count)
      }
    }
    this.onTotal();
  },
  // 跳转支付页面
  goToPay() {
    let request = this.data.list.filter(item => item.state === true)
    if (request.length === 0) {
      wx.showToast({
        title: '请勾选商品',
        icon: "none"
      })
    } else {
      wx.setStorageSync('goods', request)
      wx.navigateTo({
        url: '/pages/payinfo/payinfo?total=' + this.data.total + "&type=" + 2,
      })
    }

  },
  //删除购物车商品
  onClose(e) {
    const {
      position,
      instance
    } = e.detail;
    let that = this
    if (position == 'right') {
      wx.showModal({
        content: '确定要删除吗？',
        confirmColor: '#ff0000',
        success(res) {
          instance.close();
          if (res.confirm) {
            // 或许也可以试试连数据库
            app.removeOne('cart', e.currentTarget.dataset.id)
              .then(res => {
                that.data.list.splice(e.currentTarget.dataset.index, 1)
                that.setData({
                  list: that.data.list
                })
                that.lastOne()
                console.log('删除成功', res)
              })
              .catch(err => {
                console.log('删除失败', err)
              })
            // 删除商品功能
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  //获取推荐商品
  getProduct() {
    wx.cloud.database().collection('product_details')
      .where({
        home: "true"
      })
      .get()
      .then(res => {
        console.log("请求成功", res)
        this.setData({
          productDetails: res.data,
        })
      })
      .catch(err => {
        console.log("请求失败", err)
      })
  },
  //跳转到详情页面
  goToDetail(e) {
    wx.navigateTo({
      url: '../productDetail/productDetail?id=' + e.currentTarget.dataset.id,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    app.getList("cart")
      .then(res => {
        console.log(res.data)
        if (res.data.length != 0) {
          this.setData({
            list: res.data,
            total: 0,
            notShowBar: false
          })
          // 全选判断
          let es = this.data.list.filter(item => {
            return item.state === false
          })
          if (es.length === 0) {
            this.setData({
              checked: true
            })
          }
          // 复选框改变，计算总价
          this.onTotal()
        } else {
          this.setData({
            list: '',
            notShowBar: true,
            checked: false
          })
        }
        console.log('请求成功', res)
      })
      .catch(err => {
        console.log('请求失败', err)
      })
    this.getProduct()
    this.isLogin()
  },
  lastOne() {
    app.getList("cart")
      .then(res => {
        if (res.data.length === 0) {
          this.setData({
            notShowBar: true,
            checked: false
          })
        }
      })
      .catch(err => {
        console.log('查询失败', err)
      })
  },
})